<template>
    <div class="portfolio-learn step1">
        <div class="portfolio-common-title">
            <span></span>
            <div>调节偷师总资金</div>
        </div>
        <div class="x-bg">
            <div class="portfolio-fund">
                <input ref="initmoneyInput" id="fundInput" type="text" placeholder="请输入创建该组合所需的资金或移动下方滑条" v-model="initmoney" @click.stop.prevent @input="inputInitmoney" />
                <div v-show="loading_initSlider" class='none-data'><span><i class="iconfont icon-jiazai"></i></span></div>
                <div v-show="!loading_initSlider">
                    <div class="slider_box" ref="slider_box">
                        <div class="slider_tip" ref="slider_tip" :style="{left:'-24px'}">{{funds}}</div>
                        <div class="slider_track" ref="slider_track">
                            <div class="slider_selection" ref="slider_selection" :style="{width:'0px'}"></div>
                        </div>
                        <div class="slider_handle" ref="slider_handle" :style="{width:'20px',left:'-10px'}"></div>
                    </div>
                    <div class="portfolio-fund-text">
                        <span>剩余虚拟资金：</span>
                        <span class="fund" v-if="loading_getEnableBalance">获取中...</span>
                        <span class="fund" v-else>{{getLastFunds}}</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-info"><span>所有股票均以市价委托的方式下单</span></div>
        <div class="hbox">
            <div class="hbox-header">
                <div class="col-1 hbox-header-item">股票名称</div>
                <div class="col-2 hbox-header-item">市价</div>
                <div class="col-3 hbox-header-item">仓位</div>
                <div class="col-4 hbox-header-item">买入数量<span style="font-size:10px">(仅供参考)</span></div>
            </div>
            <div v-for="(stock,index) in stockList" class="hbox-row" :key="index">
                <div class="col-1 hbox-row-item" @click.stop.prevent="toDetails(stock)">
                    <div class="stock_name">{{stock.stockName}}</div>
                    <span class="stock_code">{{stock.marketCode}}{{stock.stockCode}}</span>
                </div>
                <div class="col-2 hbox-row-item" @click.stop.prevent="toDetails(stock)">
                    <div class="last_price color-red">{{stock.lastPrice}}</div>
                </div>
                <div class="col-3 hbox-row-item position" @click.stop.prevent="toDetails(stock)">
                    <span>{{stock.position}}</span><span>%</span>
                </div>
                <div class="col-4 hbox-row-item">
                    <input type="text" class="nVol" v-model="stock.buyNum" @click.stop.prevent @input="inputBuyNum(stock,index)" />
                    <div class="nVol_arrow">
                        <i class="iconfont icon-shang" @click.stop.prevent="addBuyNum(stock,index)"></i>
                        <i class="iconfont icon-xia" @click.stop.prevent="reduceBuyNum(stock,index)"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-balance">
            <span class="tag_red">组合剩余金额 <span class="enable_balance">{{avail_balance}}</span></span>
        </div>
        <div class="submit" @click.stop.prevent="buyIn">买入</div>
        <div class="portfolio-riskinfo">风险提示：偷师可以复制该牛人的组合仓位比，<br>您当前的操作是实盘行情，虚拟资金，请注意风险</div>
    </div>
</template>

<script>
    import LocalDAO from 'common/localDAO'
    import RemoteDAO from 'common/remoteDAO'
    import CommonUtil from 'common/common.util'
    export default {
        data () {
            return {
                user_code: LocalDAO.getUserCode(),
                enable_balance: 0,
                initmoney: 0,
                funds: 0,
                avail_balance: 0,
                lastNum: 0,
                steal_client_id: this.$route.query.clientId,
                steal_nickname: this.$route.query.nickname,
                steal_groupid: this.$route.query.groupId,
                steal_groupname: this.$route.query.groupName,
                stockList: [],
                loading_initSlider: true,
                loading_getEnableBalance: false,
                islogin: false
            }
        },
        computed: {
            getLastFunds () {
                if (this.enable_balance == 0 && this.initmoney == 0) {
                    return '获取失败'
                }
                return CommonUtil.addWangUnit(this.enable_balance - this.initmoney)
            }
        },
        watch: {
            initmoney() {
                if(this.initmoney){
                    this.funds = this.initmoney;
                }else{
                    this.funds = 0;
                }
                var slider_tip = this.$refs.slider_tip;
                var slider_track = this.$refs.slider_track;
                var slider_selection = this.$refs.slider_selection;
                var slider_handle = this.$refs.slider_handle;
                var handleWidth = parseInt(slider_handle.style.width);
                var trackWidth = parseInt(document.defaultView.getComputedStyle(slider_track).width);
                slider_tip.style.left = this.initmoney/this.enable_balance*trackWidth - slider_tip.getBoundingClientRect().width/2 + 'px';
                slider_handle.style.left = this.initmoney/this.enable_balance*trackWidth - handleWidth/2  + 'px';
                slider_selection.style.width = this.initmoney/this.enable_balance*trackWidth + 'px';
                this.calculateBuyNum();
            },
            funds () {
                this.initmoney = this.funds;
                if(this.funds == 0){
                    this.initmoney = '';
                }
                this.calculateBuyNum();
            }
        },
        created () {
            this.getStockList();
            var kv = {"usercode": this.user_code, "k2": "ZH_1"};
            TDAPP.onEvent("6001", "", kv);
            TDAPP.send();
        },
        mounted () {
            this.getEnableBalance();
        },
        methods: {

            //获取偷师组合的股票列表
            getStockList () {
                RemoteDAO.callJCL11141(this.steal_client_id, this.steal_groupid, 0, 20, response => {
                    if (response.error == 0) {
                        var stockList = response.data.body.holders;
                        for(let i=0;i<stockList.length;i++){
                            var stock = stockList[i];
                            var obj = {};
                            obj['stockName'] = stock.stock_name;
                            obj['marketCode'] = CommonUtil.getMarketCode(stock.exchange_type);
                            obj['stockCode'] = stock.stock_code;
                            obj['lastPrice'] = CommonUtil.toFixed(stock.last_price,2);
                            obj['position'] = CommonUtil.toFixed(stock.position,2);
                            var buyNum = this.initmoney*stock.position/100/stock.last_price;
                            obj['buyNum'] = parseInt(buyNum-buyNum%100);
                            this.stockList.push(obj)
                        }
                    } else {
                        this.$store.dispatch('setTip',{text:'股票持仓获取失败'})
                    }
                })
            },

            //获取用户可用资金
            getEnableBalance () {
                this.loading_initSlider = true;
                this.loading_getEnableBalance = true;
                RemoteDAO.callJCL11103(this.user_code, response => {
                    if (response.error == 0) {
                        this.enable_balance = Number(response.data.body.data[0].enable_balance);
                        if (this.enable_balance >= 1000) {
                            this.initmoney = 1000;
                        }
                    }
                    this.loading_initSlider = false;
                    this.loading_getEnableBalance = false;
                    this.$nextTick(() => {
                        this.initSlider()
                    })
                });
            },

            //初始化滑动条
            initSlider () {
                var slider_box = this.$refs.slider_box;
                var slider_tip = this.$refs.slider_tip;
                var slider_track = this.$refs.slider_track;
                var slider_selection = this.$refs.slider_selection;
                var slider_handle = this.$refs.slider_handle;
                var startX = 0;
                var endX = 0;
                var moveX = 0;
                var startPos = 0;
                var endPos = 0;
                var isTouching = false;
                var handleWidth = parseInt(slider_handle.style.width);
                var trackWidth = parseInt(document.defaultView.getComputedStyle(slider_track).width);
                slider_tip.style.left = this.initmoney/this.enable_balance*trackWidth - slider_tip.getBoundingClientRect().width/2 + 'px';
                slider_handle.style.left = this.initmoney/this.enable_balance*trackWidth - handleWidth/2  + 'px';
                slider_selection.style.width = this.initmoney/this.enable_balance*trackWidth + 'px';
                slider_handle.addEventListener('touchstart',e => {
                    e.preventDefault();
                    e.stopPropagation();
                    isTouching = true;
                    startX = e.targetTouches[0].clientX;
                    startPos = parseInt(slider_handle.style.left)
                });
                document.addEventListener('touchmove',e => {
                    if(isTouching){
                        endX = e.targetTouches[0].clientX;
                        moveX = endX - startX;
                        if(startPos+moveX+handleWidth/2 <=0){
                            slider_tip.style.left = -slider_tip.getBoundingClientRect().width/2 + 'px';
                            slider_handle.style.left = -handleWidth/2 + 'px';
                            slider_selection.style.width = 0 + 'px';
                            this.funds = 0
                        }else if(startPos+moveX+handleWidth/2 >=trackWidth){
                            slider_tip.style.left = trackWidth - slider_tip.getBoundingClientRect().width/2 + 'px';
                            slider_handle.style.left = trackWidth-handleWidth/2 + 'px';
                            slider_selection.style.width = trackWidth + 'px';
                            this.funds = Math.floor(this.enable_balance/1000)*1000;
                        }else{
                            endPos = startPos + moveX;
                            slider_tip.style.left = endPos + handleWidth/2 - slider_tip.getBoundingClientRect().width/2 + 'px';
                            slider_handle.style.left = endPos +'px';
                            slider_selection.style.width = endPos + handleWidth/2 +'px';
                            this.funds =Math.floor(parseInt(slider_selection.style.width)/trackWidth*this.enable_balance/1000)*1000;
                        }
                    }
                });
                document.addEventListener('touchend',e => {
                    isTouching = false;
                });
                slider_box.addEventListener('touchstart',e => {
                    e.preventDefault();
                    e.stopPropagation();
                    var boxLeft = slider_box.getBoundingClientRect().left;
                    slider_handle.style.left = e.targetTouches[0].clientX - boxLeft -handleWidth/2 + 'px';
                    slider_tip.style.left = e.targetTouches[0].clientX - boxLeft - slider_tip.getBoundingClientRect().width/2 + 'px';
                    slider_selection.style.width = e.targetTouches[0].clientX - boxLeft + 'px';
                    this.funds =Math.floor(parseInt(slider_selection.style.width)/trackWidth*this.enable_balance/1000)*1000;
                    isTouching = true;
                    startX = e.targetTouches[0].clientX;
                    startPos = parseInt(slider_handle.style.left);
                })
            },

            //手动输入组合初始资金
            inputInitmoney () {
                var initmoney = this.initmoney;
                if (isNaN(initmoney)) {
                    initmoney = initmoney.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
                    initmoney = initmoney.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
                    initmoney = initmoney.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
                    initmoney = initmoney.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数点
                    this.lastNum = initmoney.toString();
                    this.initmoney = initmoney;
                }
                if (initmoney.indexOf(".") > -1 && initmoney.substring(initmoney.indexOf(".") + 3, initmoney.length).length > 0) {
                    initmoney = initmoney.substring(0, initmoney.indexOf(".") + 3);//转为保留两位的数字
                    this.lastNum = initmoney.toString();
                    this.initmoney = initmoney;
                }
                if (Number(initmoney) > this.enable_balance.toFixed(2)) { //大于剩余资金则转成上次缓存的值
                    this.$store.dispatch('setTip',{text:'你没有那么多资金了'});
                    initmoney = this.lastNum;
                    this.initmoney = initmoney;
                }
                this.lastNum = initmoney;//缓存这次的值
            },

            //滑动条滑动改变组合初始资金时，重新计算每支股票的买入数量
            calculateBuyNum () {
                for(let i=0;i<this.stockList.length;i++){
                    var stock = this.stockList[i];
                    var buyNum = this.initmoney * stock.position / 100 / stock.lastPrice;
                    stock.buyNum = parseInt(buyNum-buyNum%100);
                    this.stockList.splice(i,1,stock);
                }
                this.calculateAvailBalance();
            },

            //计算剩余资金
            calculateAvailBalance () {
                var cost = 0;
                var availBalance = 0;
                for(let i=0;i<this.stockList.length;i++){
                    var stock = this.stockList[i];
                    cost += stock.lastPrice * stock.buyNum;
                }
                availBalance = this.initmoney - cost;
                if(availBalance < 0){
                    availBalance = 0;
                }
                this.avail_balance = CommonUtil.toFixed(availBalance,2);
            },

            //增加买入数量
            addBuyNum (stock,index) {
                var buyNum = Number(stock.buyNum);
                var lastPrice = Number(stock.lastPrice);
                var availBalance = Number(this.avail_balance);
                if(lastPrice*100 > availBalance){
                    this.$store.dispatch('setTip',{text:'偷师资金不足!'});
                    return;
                }
                if(buyNum % 100 == 0){
                    buyNum +=100;
                }else{
                    buyNum += 100;
                    buyNum = parseInt(buyNum -buyNum%100);
                }
                stock.position = (buyNum * lastPrice / this.initmoney * 100).toFixed(2);
                stock.buyNum = buyNum;
                this.stockList.splice(index,1,stock);
                this.calculateAvailBalance();
            },

            //减少买入数量
            reduceBuyNum (stock,index) {
                var buyNum = Number(stock.buyNum);
                var lastPrice = Number(stock.lastPrice);
                if(buyNum > 100){
                    if(buyNum % 100 ==0){
                        buyNum -= 100;
                    }else{
                        buyNum -= 100;
                        buyNum = parseInt(buyNum - buyNum%100);
                    }
                }else{
                    buyNum = 0;
                }
                stock.position = this.initmoney <= 0 ? "0.00" : (buyNum * lastPrice / this.initmoney * 100).toFixed(2);
                stock.buyNum = buyNum;
                this.stockList.splice(index,1,stock);
                this.calculateAvailBalance();
            },

            //手动输入买入数量
            inputBuyNum (stock,index) {
                var buyNum = stock.buyNum;
                if (isNaN(buyNum) || buyNum.indexOf('.') > -1) {
                    buyNum = buyNum.replace(/\D/g, '');  //清除非数字
                    stock.buyNum = buyNum;
                }
                var lastPrice = stock.lastPrice;
                stock.position = CommonUtil.toFixed(buyNum * lastPrice / this.initmoney * 100, 2);
                this.stockList.splice(index,1,stock);
                this.calculateAvailBalance();
            },

            //点击股票行到原生详情页面
            toDetails (stock) {
                var stock_code = stock.stockCode;
                if (LocalDAO.getNickname()) {
                    this.islogin = true;
                } else {
                    this.islogin = false;
                }
                RemoteDAO.callStockLive(stock_code, "ordinary", this.islogin, function (data) {});
            },

            //点击买入
            buyIn () {
                if (this.initmoney < 1000) {
                    this.$store.dispatch('setTip',{text:'组合初始资金不能小于1000'});
                    return;
                }
                var isZero = false;
                var totalPosition = 0;
                for(let i=0;i<this.stockList.length;i++){
                    var stock = this.stockList[i];
                    if(Number(stock.buyNum) == 0 || Number(stock.buyNum) % 100 != 0){
                        isZero = true;
                        break;
                    }
                    totalPosition += stock.position;
                }
                if(isZero){
                    this.$store.dispatch('setTip',{text:'买入数量需要是100的整数倍且不为0'});
                    return;
                }
                if(Number(totalPosition)>100){
                    this.$store.dispatch('setTip',{text:'总仓位大于100%了，请调整'});
                    return;
                }
                var group_wt = [];
                var group = [];
                for(let i=0;i<this.stockList.length;i++){
                    var stock = this.stockList[i];
                    var stock_code = stock.stockCode;
                    var market_code = stock.marketCode;
                    var position = stock.position;
                    var obj = {};
                    var object = {};
                    obj['exchange_type'] = CommonUtil.getExchangeType(market_code);
                    obj['stock_code'] = stock_code;
                    obj['position'] = (Number(position) / 100).toFixed(2);
                    object['stockName'] = stock.stockName;
                    object['stockCode'] = stock.stockCode;
                    object['buyNum'] = stock.buyNum;
                    group_wt.push(obj);
                    group.push(object);
                }
                group = JSON.stringify(group);
                var param = {
                    "client_id": this.user_code,
                    "initmoney": this.initmoney,
                    "group_name": "偷师" + this.steal_groupname,
                    "steal_client_id": this.steal_client_id,
                    "steal_groupid": this.steal_groupid,
                    "steal_nickname": this.steal_nickname,
                    "steal_groupname": this.steal_groupname,
                    "group_wt": JSON.stringify(group_wt)
                };
                RemoteDAO.callJCL11159(param, response => {
                    if (response.error == 0) {
                        var groupMessages = {
                            tradeType: 'learn',
                            group: group,
                            group_name: param.group_name,
                            group_id: response.data.body.group_id,
                            entrust_no: response.data.body.entrust_no
                        };
                        this.$store.dispatch('setGroupMessages',groupMessages);
                        this.$router.push('/groupreason/choosereason');
                    } else if (response.data == "该昵称的组合已经存在") {
                        param.group_name = param.group_name + CommonUtil.getNowTime();
                        RemoteDAO.callJCL11159(param, r => {
                            if (r.error == 0) {
                                var groupMessages = {
                                    tradeType: 'learn',
                                    group: group,
                                    group_name: param.group_name,
                                    group_id: r.data.body.group_id,
                                    entrust_no: r.data.body.entrust_no
                                };
                                this.$store.dispatch('setGroupMessages',groupMessages);
                                this.$router.push('/groupreason/choosereason');
                            } else if (response.data == "该昵称的组合已经存在") {
                                this.$store.dispatch('setTip',{text:'系统繁忙，请稍后重试'});
                            } else {
                                this.$store.dispatch('setTip',{text:r.data});
                            }
                        });
                    } else {
                        this.$store.dispatch('setTip',{text:response.data});
                    }
                })
            }
        }
    }
</script>

<style scoped>
    .portfolio-learn .portfolio-fund #fundInput {
        margin-bottom: 5px;
    }
    .portfolio-learn .portfolio-fund .none-data {
        margin-top: 47px;
    }
    .slider_box {
        position:relative;
        width:100%;
        height:50px;
        margin:0 auto;
    }
    .slider_box .slider_tip {
        display:inline-block;
        min-width:48px;
        padding:0 3px;
        box-sizing:border-box;
        height:24px;
        border-radius:12px;
        text-align:center;
        line-height:24px;
        background:red;
        color:#fff;
        position:absolute;
        left:-24px;
        top:0;
    }
    .slider_box .slider_tip::after {
        content:"";
        display:block;
        width:0;
        height:0;
        border:4px transparent solid;
        border-top-color:red;
        position:absolute;
        left:50%;
        top:100%;
        transform:translateX(-50%);
    }
    .slider_box .slider_track {
        width:100%;
        height:8px;
        border-radius:4px;
        background:#e5e6e6;
        overflow:hidden;
        position:absolute;
        left:50%;
        top:80%;
        -webkit-transform:translate(-50%,-50%);
    }
    .slider_box .slider_selection {
        width:0;
        height:100%;
        border-radius:4px;
        border:1px #3FB9EE solid;
        box-sizing:border-box;
        background:#82D7FF;
        box-shadow:none;
    }
    .slider_box .slider_handle {
        width:20px;
        height:20px;
        border-radius:10px;
        border:2px #fff solid;
        box-sizing:border-box;
        background:#82D7FF;
        box-shadow: 0 0 1px 1px #82D7FF;
        position:absolute;
        left:-10px;
        top:80%;
        -webkit-transform:translate(0,-50%);
    }
</style>
